package com.azr.jesus.service.impl;

import cn.hutool.core.util.StrUtil;
import com.azr.jesus.entity.SysDept;
import com.azr.jesus.entity.SysMenu;
import com.azr.jesus.mapper.SysMenuMapper;
import com.azr.jesus.service.ISysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单权限表 服务实现类
 * @author: Xiong
 * @date: 2022-11-28
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public List<SysMenu> findMenus(String name) {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> menuIds = new ArrayList<>();
        QueryWrapper<SysMenu> query = new QueryWrapper<>();
        if (StrUtil.isNotBlank(name)) {
            query.like("menu_name", name);
        }
        List<SysMenu> menus = list(query);
        for (SysMenu menu : menus) {
            menuIds.add(menu.getMenuId());
        }
        for (SysMenu menu : menus) {
            // 遍历顶级节点的所有子节点
            if (!menuIds.contains(menu.getParentId())){
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (StrUtil.isNotEmpty(n.getParentId().toString()) && n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }
}
